package com.nest.WorkNest.act;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.MyApplication;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.config.UserInfo;
import com.nest.WorkNest.tools.Constant;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.tools.VolleyHelper;
import com.nest.WorkNest.tools.imgUtils;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MyAct extends BaseActivity implements OnClickListener {
    @Bind(R.id.tv_my_username)
    TextView tvMyUsername;
    private Button btn_my_myproduct, btn_my_myrecommend, btn_my_myenquiry, btn_my_mydevelpment,
            btn_my_largeorders, btn_my_favorites, btn_my_invite, btn_my_calls, btn_my_settings,
            btn_my_transaction, btn_my_message, btn_my_login;
    private Context context = MyAct.this;
    private ImageView iv_my_icon;
    private LinearLayout ll_my_all;
    private TextView tv_my_tips;
    private BitmapUtils bitmapUtils;
    private NetworkImageView user_head;// 用户头像
    private String imgUrl;
    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constant.DESCRIPTOR);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my);
        ButterKnife.bind(this);
        initView();
        loadPerson();
        judgeLogin();
        configPlatforms();
    }

    private void initView() {
        bitmapUtils = new BitmapUtils(context);
        myApp = (MyApplication) getApplication();
        ll_my_all = (LinearLayout) findViewById(R.id.ll_my_all);
        btn_my_myproduct = (Button) findViewById(R.id.btn_my_myproduct);
        btn_my_myrecommend = (Button) findViewById(R.id.btn_my_myrecommend);
        btn_my_myenquiry = (Button) findViewById(R.id.btn_my_myenquiry);
        btn_my_mydevelpment = (Button) findViewById(R.id.btn_my_mydevelpment);
        btn_my_largeorders = (Button) findViewById(R.id.btn_my_largeorders);
        btn_my_favorites = (Button) findViewById(R.id.btn_my_favorites);
        btn_my_invite = (Button) findViewById(R.id.btn_my_invite);
        btn_my_calls = (Button) findViewById(R.id.btn_my_calls);
        btn_my_settings = (Button) findViewById(R.id.btn_my_settings);
        btn_my_transaction = (Button) findViewById(R.id.btn_my_transaction);
        btn_my_message = (Button) findViewById(R.id.btn_my_message);
        iv_my_icon = (ImageView) findViewById(R.id.iv_my_icon);
        btn_my_login = (Button) findViewById(R.id.btn_my_login);
        tv_my_tips = (TextView) findViewById(R.id.tv_my_tips);
        btn_my_myproduct.setOnClickListener(this);
        btn_my_myrecommend.setOnClickListener(this);
        btn_my_myenquiry.setOnClickListener(this);
        btn_my_mydevelpment.setOnClickListener(this);
        btn_my_largeorders.setOnClickListener(this);
        btn_my_favorites.setOnClickListener(this);
        btn_my_invite.setOnClickListener(this);
        btn_my_calls.setOnClickListener(this);
        btn_my_settings.setOnClickListener(this);
        btn_my_transaction.setOnClickListener(this);
        btn_my_message.setOnClickListener(this);
        iv_my_icon.setOnClickListener(this);
        btn_my_login.setOnClickListener(this);
    }

    public void judgeLogin() {
        if (!fileHelper.getBoolean(UserInfo.USERINFO_ISLOGIN)) {
            ll_my_all.setVisibility(View.GONE);
            tv_my_tips.setVisibility(View.VISIBLE);
            btn_my_login.setVisibility(View.VISIBLE);
        } else if (fileHelper.getBoolean(UserInfo.USERINFO_ISLOGIN)) {
            ll_my_all.setVisibility(View.VISIBLE);
            tv_my_tips.setVisibility(View.GONE);
            btn_my_login.setVisibility(View.GONE);
            loadPerson();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_my_myproduct:
                Intent pIntent = new Intent(context, MyDevelopAct.class);
                startActivity(pIntent);
                break;
            case R.id.btn_my_myrecommend:
                Intent rIntent = new Intent(context, MyRecommendAct.class);
                startActivity(rIntent);
                break;
            case R.id.btn_my_myenquiry:
                myApp.tabHostId = 1;
                myApp.tabHost.setCurrentTab(myApp.tabHostId);
                break;
            case R.id.btn_my_mydevelpment:
                Intent dIntent = new Intent(context, DevelopmentAct.class);
                startActivity(dIntent);
                break;
            case R.id.btn_my_largeorders:
                Intent lIntent = new Intent(context, BulkOrderAct.class);
                startActivity(lIntent);
                break;
            case R.id.btn_my_favorites:
                Intent fIntent = new Intent(context, MyFavoritesAct.class);
                startActivity(fIntent);
                break;
            case R.id.btn_my_invite:
                loadgetSendMessage();
                break;
            case R.id.btn_my_calls:
                Intent cIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0571-86700832"));
                startActivity(cIntent);
                break;
            case R.id.btn_my_settings:
                Intent sIntent = new Intent(context, SettingsAct.class);
                startActivity(sIntent);
                break;
            case R.id.btn_my_transaction:
                Intent tIntent = new Intent(context, TradeAct.class);
                startActivity(tIntent);
                break;
            case R.id.btn_my_message:
                Intent intent = new Intent(context, MyMsgAct.class);
                startActivity(intent);
                break;
            case R.id.iv_my_icon:
                Intent myIntent = new Intent(context, PersonalCenterAct.class);
                myIntent.putExtra("imgUrl", imgUrl);
                startActivity(myIntent);
                break;

            case R.id.btn_my_login:
                Intent lintent = new Intent(context, LoginAct.class);
                startActivity(lintent);
                break;
        }
    }

    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            showToast("再按一次退出程序");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    public void loadPerson() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    imgUrl = Tool.getString(Tool.getString(result, "user"), "headPortraits");
                    tvMyUsername.setText(Tool.getString(Tool.getString(result, "user"), "userName"));
                    user_head = (NetworkImageView) findViewById(R.id.iv_my_icon);
                    user_head.setErrorImageResId(R.drawable.default_image);
                    user_head.setIndirectBitmapListener(new NetworkImageView.IndirectBitmapListener() {
                        @Override
                        public Bitmap indirectBitmap(Bitmap bitmap) {
                            if (bitmap != null) {
                                return imgUtils.toRoundBitmap(bitmap);
                            }
                            return null;
                        }
                    });
                    if (!TextUtils.isEmpty(imgUrl))
                        if (!imgUrl.substring(0, 1).equals("h") && !imgUrl.substring(0, 1).equals("H")) {
                            imgUrl = "http://" + imgUrl;
                        }
                    user_head.setImageUrl(imgUrl, VolleyHelper.getInstance(context).getImageLoader());
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                } else {
                    showToast(Tool.getString(result, "MSG"));
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostUserDetail(context, ioAuthCallBack);
    }

    public void loadgetSendMessage() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    mController.setShareContent(Tool.getString(result, "MSG"));
                    mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                            SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA, SHARE_MEDIA.TENCENT);
                    mController.openShare((Activity) context,false);
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostgetSendMessage(context, ioAuthCallBack);
    }

    /**
     * 配置分享平台参数</br>
     */
    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        // 添加腾讯微博SSO授权
        mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
        // 添加QQ、QZone平台
        addQQQZonePlatform();

        // 添加微信、微信朋友圈平台
        addWXPlatform();
    }

    /**
     * @return
     * @功能描述 : 添加微信平台分享
     */
    private void addWXPlatform() {
        // 注意：在微信授权的时候，必须传递appSecret
        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appId = "wx967daebe835fbeac";
        String appSecret = "5bb696d9ccd75a38c8a0bfe0675559b3";
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret);
        wxHandler.addToSocialSDK();

        // 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    /**
     * @return
     * @功能描述 : 添加QQ平台支持 QQ分享的内容， 包含四种类型， 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
     * image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
     * 要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
     * : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
     */
    private void addQQQZonePlatform() {
        String appId = "100424468";
        String appKey = "c7394704798a158208a74ab60104f0ba";
        // 添加QQ支持, 并且设置QQ分享内容的target url
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this,
                appId, appKey);
        qqSsoHandler.setTargetUrl("http://www.umeng.com/social");
        qqSsoHandler.addToSocialSDK();

        // 添加QZone平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, appId, appKey);
        qZoneSsoHandler.addToSocialSDK();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;
        if(ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        if (UserInfo.TEL_PHONE != null)
            judgeLogin();
        super.onResume();
    }
}
